<script setup lang="ts">
import { uploadFileAPI } from '@/apis/common';
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from '@/apis/enterprise';
import type { EnterpriseParams, Industry } from '@/types/enterprise';
import { CircleCheck, Upload } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: 0 // 营业执照id
}) 
// 表单规则
const addRules = ref<FormRules<EnterpriseParams>>({
  name: [
    { required: true, message: '企业名称为必填', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '法人为必填', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '注册地址为必填', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '所在行业为必填', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '企业联系人为必填', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: 'blur' },
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
})
// 表单组件实例，用于 表单整体校验 和 表单重置
const formRef = ref<FormInstance>()
const router = useRouter()
// 加载状态按钮（禁止提交，避免重复提交）
const submitLoading = ref(false)

// 确认提交
const onSubmit = async () => {
  try {
    // 表单提交前，统一校验
    await formRef.value?.validate();
    // 把提交按钮置为加载状态 禁止提交，避免重复提交
    submitLoading.value = true
    // 根据是否有id值，判断是编辑还是新增
    // 提取后端所需参数
    const submitData = {
      name: addForm.value.name,
      legalPerson: addForm.value.legalPerson,
      registeredAddress: addForm.value.registeredAddress,
      industryCode: addForm.value.industryCode,
      contact: addForm.value.contact,
      contactNumber: addForm.value.contactNumber,
      businessLicenseUrl: addForm.value.businessLicenseUrl,
      businessLicenseId: addForm.value.businessLicenseId,
      id:addForm.value.id
    }
    if(addForm.value.id){
      
      await updateEnterpriseAPI(submitData)
      ElMessage.success('编辑成功')
    }else{
      // 提交表单给后端
    await createEnterpriseAPI(addForm.value)
    ElMessage.success('添加企业成功')
    }
    router.back()
  } catch {
    // 提交失败，恢复按钮状态
    submitLoading.value = false
  }
}

// 重置表单
const onReset = () => {
  formRef.value?.resetFields()
  fileList.value = []
}
// 获取行业列表
const industryList = ref<Industry[]>([])
const getIndustryList = async () => {
  const res = await getIndustryListAPI()
  industryList.value = res.data
}
getIndustryList()
const fileList = ref<UploadUserFile[]>([])
// 上传营业执照
const uploadFile = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')
  const res =  await uploadFileAPI(fd)
  // 单独校验表单，如果校验成功，自动清除错误信息
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  formRef.value?.validateField('businessLicenseUrl')
  return res.data.url
}
// 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
const beforeUpload = (file:UploadRawFile)=>{
  // 验证文件类型,includes返回布尔值
  const allowImageType = ['image/jpeg', 'image/png','image/jpg'].includes(file.type)
  // 最多5M
  const allowImageSize = file.size / 1024 / 1024 < 5
  if(!allowImageType){
    ElMessage.error('上传文件只能是 jpg、png、jpeg 格式!')
  } 
  if(!allowImageSize){
    ElMessage.error('上传文件大小不能超过 5MB!')
  }
  return allowImageType && allowImageSize
}
// @remove 图片移除时的钩子
const removeUploadFile = () => {
  // 清除营业执照的 URL 和 ID
  addForm.value.businessLicenseUrl = ''
  addForm.value.businessLicenseId = undefined
  formRef.value?.validateField('businessLicenseUrl')
}
const route = useRouter()
const getDetail = async (id:string) => {
  const res = await getEnterpriseDetailAPI(id)
  // 回显表单数据
  addForm.value = {
    ...res.data,
    id:res.data.id.toString()
  }
  // 回显营业执照
  fileList.value = [
    {
      name: res.data.businessLicenseName,
      url: res.data.businessLicenseUrl
    }
  ]
}
// 根据路由参数判断是否需要回显数据
if (route.currentRoute.value.params.id) {
  getDetail(route.currentRoute.value.params.id as string)
}
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="$route.params.id? '编辑企业':'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form 
          ref="formRef" 
          label-width="100px"
           :model="addForm"
           :rules="addRules"
          >
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item  label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
              :http-request="uploadFile"
              list-type="picture"
              :limit="1"
              v-model:file-list="fileList"
              :before-upload="beforeUpload"
              accept=".jpg,.png,.jpeg"
              @remove="removeUploadFile"
              >
              <el-button v-if="fileList.length === 0" type="primary">
                <el-icon><Upload/></el-icon>
                上传营业执照</el-button>
                <el-button v-else type="success" disabled :icon="CircleCheck" >已上传</el-button>
              <template #tip>
                <div class="el-upload__tip">支持拓展名:png,jpg,jpeg,上传文件大小不超过5M</div>
              </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset()">重置</el-button>
        <el-button @click="onSubmit()" type="primary" :loading="submitLoading">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>